<template>
  <div class="box">
     <fou-dialog :title="'發票'" v-model:dialogValue="dialogValue" :width="'75%'">
      <template #content>
    <el-form :model="form" label-width="100px" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="日期" prop="create_time"><el-input v-model="form.create_time" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="員工" prop="username"><el-input v-model="form.username" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="學校" prop="school"><el-input v-model="form.school_name" disabled  /></el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="學生" prop="student_id">
              <el-button v-show="form.student_name" >{{form.student_name}}</el-button>
              <el-button  @click="addStudentTable" type="primary" circle icon="Search"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="狀態" prop="status">
                <el-select  v-model="form.status"  size="default" >
                  <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
          </el-form-item>
        </el-col>

         <el-col :span="24">
          <el-form-item label="備註" prop="remark">
            <el-col :span="22">
              <el-input type="textarea" v-model="form.remark" ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="Search" circle @click="addRemarks('1','remark')">
              </el-button>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客戶須知" prop="notice">
            <el-col :span="22">
              <el-input type="textarea" v-model="form.notice" ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="Search" circle @click="addRemarks('2','notice')">
              </el-button>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="course">
          <el-form-item label="套票/產品">
            <!-- onShowProduct() -->
            <el-button @click="addCourseProductsList('course','coursecate','courseList')" color="#50BC58"
              icon="ZoomIn">課程
            </el-button>
            <el-button @click="addCourseProductsList('product','producttype','productList')" color="#50BC58"
              icon="ZoomIn">產品
            </el-button>
            <el-button @click="addCourseProductsList('productGroup','producttype','productGroupList')" color="#50BC58"
              icon="ZoomIn">產品組合</el-button>
            <el-button @click="addTicket" color="#50BC58" icon="ZoomIn">套票</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs type="border-card" v-model="cardName">
            <el-tab-pane label="課程" name="course">
              <course :list="formData.joinData.courseList" :discountSelect="discountSelect"
               @del_course="(v)=>{delcourse('courseList',v)}"
               @input="(v)=>{onProductInput('courseList',v)}"
              @select="(v)=>{onProductSelect('courseList',v)}"
               @sign="handleSign"
              @delSign="handleDelSign"
              ref="courseRef"
               ></course>
            </el-tab-pane>
            <el-tab-pane label="產品"  name="product">
              <product :list="formData.joinData.productList"   :discountSelect="discountSelect"
               @del_course="(v)=>{delcourse('productList',v)}"
               @input="(v)=>{onProductInput('productList',v)}"
              @select="(v)=>{onProductSelect('productList',v)}"
              ></product>
            </el-tab-pane>
            <el-tab-pane label="產品組合" name="productGroup">
              <productGroup :list="formData.joinData.productGroupList"   :discountSelect="discountSelect"
               @del_course="(v)=>{delcourse('productGroupList',v)}"
               @input="(v)=>{onProductInput('productGroupList',v)}"
              @select="(v)=>{onProductSelect('productGroupList',v)}"
              > </productGroup>
            </el-tab-pane>
            <el-tab-pane label="套票" name="ticket">
              <ticket :list="formData.joinData.ticketList"  :discountSelect="discountSelect"
              @del_course="(v)=>{delcourse('ticketList',v)}"
               @input="(v)=>{onTicket('input',v)}"
                @select="(v)=>{onTicket('select',v)}"
              ></ticket>
            </el-tab-pane>
      </el-tabs>
    </el-form>
        <div class="flex justify-start mt-[20px]">發票總數：{{invoiceData.num}}</div>
    <div  class="flex justify-start">發票金額：{{invoiceData.amount}}</div>
           <div class="flex justify-end mt-10 w-[100%]" >
            <el-button @click="dialogValue = false">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef,buttonType)" color="#081F42">確定</el-button>
           </div>
      </template>
     </fou-dialog>
     <notes ref="notesRef" @update="getNotes"></notes>
    <studentDio ref="studentRef" @update="getStudent"></studentDio>
    <CourseProductsDio ref="CourseProductsRef" @update="getCourseProducts"></CourseProductsDio>
    <ticketDio ref="ticketRef" @update="getTicket"></ticketDio>
     <Registration ref="RegistrationRef" @save="handleSave"></Registration>

  </div>
</template>

<script setup>
import { ref, reactive,onMounted, watch,computed } from "vue";
import {message} from '@/common/function.js'
import { dayjs } from "element-plus";
import notes from './notes/notes.vue'
import studentDio from './student.vue'
import CourseProductsDio from './CourseProducts.vue'
import Registration from './tableList/registration.vue'
import ticketDio from './ticket.vue'
  import {
    subtract,
    multiply,
    divide,
    add
  } from 'high-precision-four-fundamental-rules'
import course from './tableList/course.vue'
import product from './tableList/product.vue'
import productGroup from './tableList/productGroup.vue'
import ticket from './tableList/ticket.vue'
import {discounts,addInvoice,updateInvoice} from '@/http/index.js'
// 添加課程、產品、產品組合列表
const formData = reactive({
          joinData: {
            courseList: [], //課程
            productList: [], //產品
            productGroupList: [], //產品組合
            ticketList:[]//
          }
})
const invoiceData = computed(()=>{
          let num = 0,
          amount = 0;
          for (let key in formData.joinData) {
          num += formData.joinData[key] && formData.joinData[key].length
          if (formData.joinData[key].length > 0) {
            formData.joinData[key].forEach(v => {
              console.log(v);
              if (v.status != -1) amount += Number(v.total_prices);
            })
          }
        }
        return {
          num: num,
          amount: amount
        }
})
const form = reactive({
    school_id:localStorage.getItem('school_id'),
    create_time:dayjs().format('YYYY-MM-DD HH:mm:ss'),
    username:localStorage.getItem('username'),
    school_name:localStorage.getItem('school_name'),
    data: [],
    student_id:'',
    remark:'',
    notice:'',
    student_name:'',
    price:invoiceData.value.amount
});
const props = defineProps({
  echo:Object,
})
console.log(props.echo);
Object.assign(form,props.echo)
formData.joinData.courseList = props.echo.course
formData.joinData.productList = props.echo.product
formData.joinData.productGroupList = props.echo.products_group
formData.joinData.ticketList = props.echo.ticket
watch(()=>props.echo,(neaval)=>{
  console.log(neaval);
  Object.assign(form,neaval)
formData.joinData.courseList = neaval.course
formData.joinData.productList = neaval.product
formData.joinData.productGroupList = neaval.products_group
formData.joinData.ticketList = neaval.ticket
})
const rules = reactive({
  student_id: [{ required: true, message: "請選擇學生", trigger: ["blur",'change'] }],
  status: [{ required: true, message: "請選擇狀態", trigger: ["blur",'change'] }],
});
// 报名
const RegistrationRef = ref('')
const handleSign = (obj)=>{
    RegistrationRef.value.init(obj,form.student_id)
}

//課程報名刪除
const courseRef = ref('')
const handleDelSign = (indexA, indexB)=>{
          let list = formData.joinData.courseList[indexA].class
          courseRef.value.multiple(indexA)
          
         if (list[indexB].hasOwnProperty('id')) {
          formData.joinData.courseList[indexA].class[indexB].type = '-1'
        } else {
          formData.joinData.courseList[indexA].class.splice(indexB, 1)
        }
      setTimeout(()=>{
          courseRef.value.multiple(indexA)
      },100)
}
const handleSave = (obj)=>{
       const {data,index} = obj
        formData.joinData.courseList[index].class = data
return
  //  if (formData.joinData.courseList[index].hasOwnProperty('class')) {
  //   console.log(data);
  //         list = data
  //       } else {
  //         list = data
  //       }

        // formData.joinData.courseData[index].number = formData.joinData.courseData[index].number || list.length
        // this.$forceUpdate()

}
//套票 輸入|折扣選擇
      const onTicket=(type, data)=> {
        console.log(type, data);
        let item = formData.joinData['ticketList'][data.index]
        if (data.key === 'discount_id') {
          item.discount = data.item && data.item.discount
        }
        Object.assign(item, getComputeMoney(item))
      }
      //課程|產品|產品組合 輸入
     const onProductInput=(indexStr, data) =>{
      console.log(indexStr, data);
        let item = formData.joinData[indexStr][data.index]
        console.log(item,'item');
        let totalprice = null
        switch (data.key) {
            case 'num':
            item.num = data.val*1
            totalprice = (data.val * item.price)
            break;
          case 'price':
            item.price = data.val*1
            totalprice = (data.val * item.num)
            console.log(totalprice);
            break;
          case 'discount':
            item.discount_price = data.val*1
            totalprice = (item.price * item.num)
            break;
        }
            if (item.discount && item.discount.indexOf('%') > -1) {
          item.total_prices = totalprice - (totalprice * (parseInt(item.discount) * 0.01))
        } else if (item.discount) {
          item.total_prices = totalprice - 0
        } else {
          item.total_prices = totalprice
        }
        // item.total_prices = subtract(item.total_prices, Number(item.discount_price || 0), 2)
        item.total_prices = item.total_prices-Number(item.discount_price)
        if (item.total_prices < 0) {
          item.total_prices = totalprice
          item.discount_price = 0
          item.discount = ''
          item.discount_id = ''
          message('折扣超出付款金額','warning')
        }
      }
      //課程|產品|產品組合 折扣下拉選擇
     const onProductSelect=(indexStr, data)=> {
      console.log(indexStr, data);
        let item = formData.joinData[indexStr][data.index]
        console.log(item);
        let totalprice = item.num * item.price
        let diffVal = null
        let discount = null
        if (Boolean(data.item)) {
          item.discount_id = data.item.id
          item.discount = data.item.discount
          discount = data.item.discount
        } else {
          discount = 0
        }
        if (discount.toString().indexOf('%') > -1) {
          diffVal = (totalprice * (parseInt(discount) * 0.01))
        } else {
          item.discount = ''
          item.discount_id = ''
          diffVal = 0
           message('該折扣格式不正確不可用','warning')
        }
        // item.total_prices = subtract(totalprice, (diffVal + parseInt(item.discount_price ||
        //   0)), 2)
        item.total_prices = totalprice-diffVal-parseInt(item.discount_price)
        if (item.total_prices < 0) {
          item.total_prices = totalprice
          item.discount_price = 0
          item.discount = ''
          item.discount_id = ''
          message('折扣超出付款金額','warning')
        }
      }
const getCourseProducts = (row,type,indexUrl)=>{
       let equation = row.filter(item => !formData.joinData[indexUrl].some(y => y.id === item.id))
       console.log(equation);
       if (equation.length != 0 ) {
          formData.joinData[indexUrl] = [...formData.joinData[indexUrl],...equation]
       }else{
            message('重複選項不可選','warning')
       }
}
const delcourse = (indexStr,row)=>{
  console.log(indexStr,row);
  let item = formData.joinData[indexStr]
  formData.joinData[indexStr]  = item.filter(item => item.id != row.id)
}
// 添加套票列表
const getTicket = (row)=>{
  console.log(row);
        let equation = row.filter(item => !formData.joinData.ticketList.some(y => y.id === item.id))
       if (equation.length != 0 ) {
        let list = [...equation]
        console.log(list,'list');
        // item.deadline = item.ticket_item[0].deadline
        list = list.map(item => {
          item.discount = ''
          item.discount_price = 0
          item.discount_id = ''
          item.status = 1
          item.inputVal = 0
          item.isWeb = true
          item.num = 1
          item.cId = item.id
          item.type_name = 'ticket'
          item.deadline = item.ticket_item[0].deadline
          Object.assign(item, getComputeMoney(item))
          // delete item.id
          return item
        })
          formData.joinData.ticketList = [...formData.joinData.ticketList,...equation]
       }else{
            message('重複選項不可選','warning')
       }

}

const getComputeMoney = (item)=>{
  console.log(item);
          let indexStr = 'price'
        let isPercent = false
        let diffVal = 0
        let selfNumber = Number(item.num)
        if (item.discount && item.discount !== '') {
          isPercent = item.discount.indexOf('%') > -1 ? true : false //是否百分比符號
          // diffVal = isPercent ? parseInt(item.discount) * 0.01 : 0
          if (isPercent) {
            diffVal = parseInt(item.discount)* 0.01
          }else{
            diffVal = 0 
            item.discount = ''
          item.discount_id = ''
          diffVal = 0
           message('該折扣格式不正確不可用','warning')
            }
        } else {
          diffVal = 0
        }

        for (let i = 0, leng = item.ticket_item.length; i < leng; i++) {
          let num = Number(item.ticket_item[i].num)
          let deadline = item.ticket_item[i].deadline
          let priceNum = 0
          let discountNum = 0
          if (selfNumber >= num) { //判斷 輸入值大於等於循環對比值
            if (num <= 0) {
              priceNum = multiply(selfNumber, (Number(item.ticket_item[i][indexStr]) / Number(item.ticket_item[i].num)),2)
              item.price = divide(Number(item.ticket_item[i][indexStr]), Number(item.ticket_item[i].num), 2)
              item.total_prices = 0
              if (item.total_prices < 0) {
                item.total_prices = 0
                item.discount_price = 0
                item.discount = ''
                item.discount_id = ''
                message('折扣超出付款金額！','warning')
              }
              item.deadline = deadline
              item.formula =
                `計算公式：(金額(${item.ticket_item[i][indexStr]}) ÷ 數量(${num})) × 輸入數量(${selfNumber}) - 特別折扣(${isPercent?multiply(priceNum,diffVal,2):diffVal}) - 折扣(${item.discount_price}) = 總價錢(${item.total_prices})`
            } else {
              priceNum = multiply(selfNumber, (Number(item.ticket_item[i][indexStr]) / Number(item.ticket_item[i]
                  .num)),
                2)
              item.price = divide(Number(item.ticket_item[i][indexStr]), Number(item.ticket_item[i].num), 2)
              discountNum = isPercent ? add(item.discount_price, multiply(priceNum, diffVal, 2), 2) : add(item
                .discount_price,
                diffVal, 2)
              item.total_prices = subtract(priceNum, discountNum, 2)
              if (item.total_prices < 0) {
                item.total_prices = priceNum
                item.discount_price = 0
                item.discount = ''
                item.discount_id = ''
                this.$message.warning('折扣超出付款金額！')
              }
              item.deadline = deadline
              item.formula =
                `計算公式：(金額(${item.ticket_item[i][indexStr]}) ÷ 數量(${item.ticket_item[i].num})) × 輸入數量(${selfNumber}) - 特別折扣(${isPercent?multiply(priceNum,diffVal,2):diffVal}) - 折扣(${item.discount_price}) = 總價錢(${item.total_prices})`
            }
          } else {
            if (i === 0) {
              priceNum = multiply(selfNumber, (Number(item.ticket_item[0][indexStr]) / Number(item.ticket_item[0]
                  .num)),
                2)
              item.price = divide(Number(item.ticket_item[0][indexStr]), Number(item.ticket_item[0].num), 2)
              discountNum = isPercent ? add(item.discount_price, multiply(priceNum, diffVal, 2), 2) : add(item
                .discount_price,
                diffVal, 2)
              item.total_prices = subtract(priceNum, discountNum, 2)
              if (item.total_prices < 0) {
                item.total_prices = priceNum
                item.discount_price = 0
                item.discount = ''
                item.discount_id = ''
                this.$message.warning('折扣超出付款金額！')
              }
              item.deadline = deadline
              item.formula =
                `計算公式：(金額(${item.ticket_item[0][indexStr]}) ÷ 數量(${item.ticket_item[0].num})) × 輸入數量(${selfNumber}) - 特別折扣(${isPercent?multiply(priceNum,diffVal,2):diffVal}) - 折扣(${item.discount_price}) = 總價錢(${item.total_prices})`
            }
          }
        }
        //通過循環數據，能夠整減為零即應用該計算方式
        item.ticket_item = item.ticket_item.map(v => {
          let price = multiply(selfNumber, (Number(v[indexStr]) / Number(v.num)), 2)
          let discount = isPercent ? add(item.discount_price, multiply(price, diffVal, 2), 2) : add(item
            .discount_price,
            diffVal, 2)
          let num = item.total_prices - subtract(price, discount, 2)
          if (num === 0 && selfNumber !== 0) {
            v.isFlag = true
          } else {
            v.isFlag = false
          }
          return v
        })
        return item
}

// 添加學生
const getStudent = (row)=>{
  form.student_name = row.name
  form.student_id = row.id
}

const ruleFormRef = ref('')
const dialogValue = ref(false);
const buttonType = ref('')

const CourseProductsRef = ref('')
const cardName = ref('course')//卡片切換
const addCourseProductsList = async(url,type_url,indexUrl)=>{
    cardName.value = url
    CourseProductsRef.value.indexUrl = indexUrl //點擊哪一分類
    CourseProductsRef.value.TableDatatype(type_url)//類別
    await CourseProductsRef.value.TableData(url)//列表
    CourseProductsRef.value.CourseProductsDia = true
}
const ticketRef = ref('')
const addTicket = async()=>{
  cardName.value = 'ticket'
    await ticketRef.value.TableData()
  ticketRef.value.dialogValue = true
}
const notesRef = ref('')
const addRemarks = async (type,name)=>{
  await notesRef.value.TableData(type)
  notesRef.value.dialogValue = true
  notesRef.value.name = name
}
const studentRef = ref('')
const addStudentTable = async()=>{
  await studentRef.value.TableData()
  studentRef.value.studentDia = true
}

const status_options = [
  {
    value: 1,
    label: '正常',
  },{
    value: -1,
    label: '作廢',
  }
]
const emit = defineEmits(['addConfirm'])
const confirm = async (formEl,type) => {
  console.log(formData.joinData);
  if (!formEl) return;
    formEl.validate(async (e)=>{
      if (e) {
        if (formData.joinData.courseList.length ==0 && 
            formData.joinData.productList.length ==0 && 
            formData.joinData.productGroupList.length ==0 && 
            formData.joinData.ticketList.length ==0) {
          return message('請至少選擇課程|產品|產品組合|套票 之一','warning')
        }

        if (type == 'add') {
          let course = formData.joinData.courseList.map(e=>({
          id:e.id,
          name:e.name,
          type:'3',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price,
          course:e.class,
        }))
        let product = formData.joinData.productList.map(e=>({
          id:e.id,
          name:e.name,
          type:'1',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        let productGroup = formData.joinData.productGroupList.map(e=>({
          id:e.id,
          name:e.name,
          type:'2',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        let ticket = formData.joinData.ticketList.map(e=>({
          id:e.id,
          name:e.name,
          type:'4',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price,
          deadline:e.deadline
        }))
        form.data = [...course,...product,...productGroup,...ticket]
        form.price = invoiceData.value.amount
            const data = await addInvoice(form)
            if (data.code == 200) {
              emit('addConfirm')
              message('添加發票成功')
              dialogValue.value = false
            }
        }
        if (type == 'edit') {
          let course = formData.joinData.courseList.map(e=>({
          id:e.cid,
          name:e.name,
          type:'3',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price,
          course:e.class,
        }))
        let product = formData.joinData.productList.map(e=>({
          id:e.cid,
          name:e.name,
          type:'1',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        let productGroup = formData.joinData.productGroupList.map(e=>({
          id:e.cid,
          name:e.name,
          type:'2',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        let ticket = formData.joinData.ticketList.map(e=>({
          id:e.cid,
          name:e.name,
          type:'4',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price,
          deadline:e.deadline
        }))
        form.data = [...course,...product,...productGroup,...ticket]
        form.price = invoiceData.value.amount
            const data = await updateInvoice(form)
            if (data.code == 200) {
              emit('addConfirm')
              message('修改發票成功')
              dialogValue.value = false
            }
        }

      }
    })
};

// 添加备注须知信息
const getNotes = (row,name)=>{
    console.log(row,name);
    if (name == 'remark') {
      form.remark = row.content
    }
    if (name == 'notice') {
      form.notice = row.content
    }

}

defineExpose({
  dialogValue,buttonType
});
const discountSelect = ref([])
const getDiscounts = async()=>{
  let obj = {limit:100}
  const data = await discounts(obj)
  console.log(data);
  if (data.code == 200) {
    discountSelect.value = data.data.data
  }
}
onMounted(()=>{
const begin = dayjs().format('YYYY-MM-DD HH:mm:ss');
getDiscounts()
})
</script>

<style lang='less'  scoped>
.course{
.el-button {
  color: #fff;
}
}

.el-col{
  padding-left: 0 !important;
}
.box{
  :deep(.el-dialog__title){
  display: flex ;
  justify-content: flex-start;
  }
}

</style>